package com.lkd.handler;


import com.github.wxpay.plus.WxPayTemplate;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.OrderCheck;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.entity.OrderEntity;
import com.lkd.service.OrderService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
@Topic(TopicConfig.ORDER_CHECK_TOPIC)
public class OrdeCheckHandler implements MsgHandler {
    @Autowired
    private OrderService orderService;

    @Autowired
    private WxPayTemplate wxPayTemplate;
    /**
     * 支付超时处理
     * @param jsonMsg
     * @throws IOException
     */
    @Override
    public void process(String jsonMsg) throws IOException {
        log.info("订单支付超时处理");
        OrderCheck orderCheck = JsonUtil.getByJson(jsonMsg, OrderCheck.class);
        if (orderCheck == null || StringUtils.isBlank(orderCheck.getOrderNo())) {
            log.info("传入参数不能为空");
            return;
        }
        OrderEntity orderEntity = orderService.getByOrderNo(orderCheck.getOrderNo());
        if (orderEntity == null){
            log.info("订单不存在");
            return;
        }
        if (orderEntity.getPayStatus().equals(VMSystem.PAY_STATUS_NOPAY)){
            log.info("订单超时未支付，订单编号：{}",orderCheck.getOrderNo());
            //关闭订单支付
            wxPayTemplate.cancelPay(orderCheck.getOrderNo());
            //订单状态改为失效
            orderEntity.setStatus(VMSystem.ORDER_STATUS_INVALID);
            orderService.updateById(orderEntity);
        }
    }
}
